"""
Website Management CLI Commands.

This module provides command-line interface for managing website profiles,
including adding, listing, removing, and updating website configurations.
"""

import argparse
import json
import sys
from typing import Dict, Any, Optional
from pathlib import Path

from models import WebsiteProfile, AuthMethod, create_default_website_profile
from website_manager import WebsiteManager
from session_manager import SessionManager


class WebsiteCLI:
    """Command-line interface for website profile management."""
    
    def __init__(self):
        """Initialize the Website CLI."""
        self.website_manager = WebsiteManager()
        self.session_manager = SessionManager()
    
    def add_website(self, args) -> bool:
        """Add a new website profile."""
        try:
            # Create profile from arguments
            profile = create_default_website_profile(
                website_id=args.id,
                display_name=args.name,
                target_url=args.url
            )
            
            # Set optional fields
            if args.login_url:
                profile.login_url = args.login_url
            
            if args.auth_method:
                profile.auth_method = AuthMethod(args.auth_method)
            
            # Set selectors if provided
            if args.username_selector:
                profile.selectors.username_field = args.username_selector
            if args.password_selector:
                profile.selectors.password_field = args.password_selector
            if args.submit_selector:
                profile.selectors.submit_button = args.submit_selector
            
            # Set browser configuration
            if args.viewport:
                try:
                    width, height = map(int, args.viewport.split('x'))
                    profile.browser_config.viewport = {"width": width, "height": height}
                except ValueError:
                    print("❌ Invalid viewport format. Use WIDTHxHEIGHT (e.g., 1920x1080)")
                    return False
            
            if args.timeout:
                profile.session_config.timeout_hours = args.timeout
            
            # Add the profile
            success = self.website_manager.add_profile(profile, overwrite=args.overwrite)
            
            if success:
                print(f"✅ Successfully added website profile: {args.id}")
                print(f"   Name: {args.name}")
                print(f"   URL: {args.url}")
                if args.login_url:
                    print(f"   Login URL: {args.login_url}")
                print(f"   Auth Method: {profile.auth_method.value}")
                return True
            else:
                print(f"❌ Failed to add website profile: {args.id}")
                return False
                
        except Exception as e:
            print(f"❌ Error adding website: {e}")
            return False
    
    def list_websites(self, args) -> bool:
        """List website profiles."""
        try:
            profiles = self.website_manager.list_profiles(include_templates=args.include_templates)
            
            if not profiles:
                print("📝 No website profiles found.")
                if not args.include_templates:
                    print("💡 Use --include-templates to see built-in templates")
                return True
            
            if args.format == "json":
                # JSON output
                profiles_data = [profile.to_dict() for profile in profiles]
                print(json.dumps(profiles_data, indent=2, ensure_ascii=False))
            else:
                # Table output
                print(f"📋 Found {len(profiles)} website profile(s):")
                print()
                
                for i, profile in enumerate(profiles, 1):
                    template_marker = ""
                    if args.include_templates and profile.website_id in self.website_manager.list_templates():
                        template_marker = " (Template)"
                    
                    print(f"{i}. {profile.display_name}{template_marker}")
                    print(f"   ID: {profile.website_id}")
                    print(f"   URL: {profile.target_url}")
                    if profile.login_url:
                        print(f"   Login URL: {profile.login_url}")
                    print(f"   Auth Method: {profile.auth_method.value}")
                    print(f"   Timeout: {profile.session_config.timeout_hours} hours")
                    print(f"   Extensions Backup: {'Yes' if profile.session_config.backup_extensions else 'No'}")
                    
                    if profile.created_at:
                        print(f"   Created: {profile.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
                    
                    print()
            
            return True
            
        except Exception as e:
            print(f"❌ Error listing websites: {e}")
            return False
    
    def remove_website(self, args) -> bool:
        """Remove a website profile."""
        try:
            # Check if profile exists
            profile = self.website_manager.get_profile(args.id)
            if not profile:
                print(f"❌ Website profile not found: {args.id}")
                return False
            
            # Confirm removal unless forced
            if not args.force:
                print(f"⚠️  This will remove the website profile:")
                print(f"   ID: {profile.website_id}")
                print(f"   Name: {profile.display_name}")
                print(f"   URL: {profile.target_url}")
                
                confirm = input("\nAre you sure? (y/N): ").strip().lower()
                if confirm not in ['y', 'yes']:
                    print("🚫 Operation cancelled")
                    return False
            
            # Remove the profile
            success = self.website_manager.remove_profile(args.id)
            
            if success:
                print(f"✅ Successfully removed website profile: {args.id}")
                return True
            else:
                print(f"❌ Failed to remove website profile: {args.id}")
                return False
                
        except Exception as e:
            print(f"❌ Error removing website: {e}")
            return False
    
    def update_website(self, args) -> bool:
        """Update an existing website profile."""
        try:
            # Check if profile exists
            profile = self.website_manager.get_profile(args.id)
            if not profile:
                print(f"❌ Website profile not found: {args.id}")
                return False
            
            # Prepare updates
            updates = {}
            
            if args.name:
                updates['display_name'] = args.name
            if args.url:
                updates['target_url'] = args.url
            if args.login_url:
                updates['login_url'] = args.login_url
            if args.auth_method:
                updates['auth_method'] = AuthMethod(args.auth_method)
            if args.timeout:
                updates['session_config'] = {'timeout_hours': args.timeout}
            
            # Handle selectors
            selectors_updates = {}
            if args.username_selector:
                selectors_updates['username_field'] = args.username_selector
            if args.password_selector:
                selectors_updates['password_field'] = args.password_selector
            if args.submit_selector:
                selectors_updates['submit_button'] = args.submit_selector
            
            if selectors_updates:
                updates['selectors'] = selectors_updates
            
            # Handle browser config
            browser_updates = {}
            if args.viewport:
                try:
                    width, height = map(int, args.viewport.split('x'))
                    browser_updates['viewport'] = {"width": width, "height": height}
                except ValueError:
                    print("❌ Invalid viewport format. Use WIDTHxHEIGHT (e.g., 1920x1080)")
                    return False
            
            if browser_updates:
                updates['browser_config'] = browser_updates
            
            if not updates:
                print("⚠️  No updates specified")
                return False
            
            # Apply updates
            success = self.website_manager.update_profile(args.id, updates)
            
            if success:
                print(f"✅ Successfully updated website profile: {args.id}")
                
                # Show updated fields
                print("📝 Updated fields:")
                for field, value in updates.items():
                    if isinstance(value, dict):
                        print(f"   {field}: {json.dumps(value, ensure_ascii=False)}")
                    else:
                        print(f"   {field}: {value}")
                
                return True
            else:
                print(f"❌ Failed to update website profile: {args.id}")
                return False
                
        except Exception as e:
            print(f"❌ Error updating website: {e}")
            return False
    
    def show_website(self, args) -> bool:
        """Show detailed information about a website profile."""
        try:
            profile = self.website_manager.get_profile(args.id)
            if not profile:
                print(f"❌ Website profile not found: {args.id}")
                return False
            
            print(f"📋 Website Profile: {profile.display_name}")
            print(f"{'='*50}")
            print(f"ID: {profile.website_id}")
            print(f"Name: {profile.display_name}")
            print(f"Target URL: {profile.target_url}")
            
            if profile.login_url:
                print(f"Login URL: {profile.login_url}")
            
            print(f"Auth Method: {profile.auth_method.value}")
            
            # Selectors
            if any([profile.selectors.username_field, profile.selectors.password_field, profile.selectors.submit_button]):
                print(f"\n🎯 Selectors:")
                if profile.selectors.username_field:
                    print(f"   Username: {profile.selectors.username_field}")
                if profile.selectors.password_field:
                    print(f"   Password: {profile.selectors.password_field}")
                if profile.selectors.submit_button:
                    print(f"   Submit: {profile.selectors.submit_button}")
            
            # Browser config
            print(f"\n🌐 Browser Configuration:")
            print(f"   Viewport: {profile.browser_config.viewport['width']}x{profile.browser_config.viewport['height']}")
            if profile.browser_config.user_agent:
                print(f"   User Agent: {profile.browser_config.user_agent}")
            if profile.browser_config.extra_args:
                print(f"   Extra Args: {', '.join(profile.browser_config.extra_args)}")
            
            # Session config
            print(f"\n⏱️  Session Configuration:")
            print(f"   Timeout: {profile.session_config.timeout_hours} hours")
            print(f"   Auto Refresh: {'Yes' if profile.session_config.auto_refresh else 'No'}")
            print(f"   Backup Extensions: {'Yes' if profile.session_config.backup_extensions else 'No'}")
            
            # Timestamps
            if profile.created_at:
                print(f"\n📅 Created: {profile.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
            if profile.updated_at:
                print(f"📅 Updated: {profile.updated_at.strftime('%Y-%m-%d %H:%M:%S')}")
            
            return True
            
        except Exception as e:
            print(f"❌ Error showing website: {e}")
            return False
    
    def create_from_template(self, args) -> bool:
        """Create website profile from built-in template."""
        try:
            # Check if template exists
            available_templates = self.website_manager.list_templates()
            if args.template not in available_templates:
                print(f"❌ Template not found: {args.template}")
                print(f"Available templates: {', '.join(available_templates)}")
                return False
            
            # Create profile from template
            profile = self.website_manager.create_from_template(
                template_id=args.template,
                website_id=args.id,
                display_name=args.name,
                target_url=args.url
            )
            
            if not profile:
                print(f"❌ Failed to create profile from template: {args.template}")
                return False
            
            # Override any additional settings
            if args.login_url:
                profile.login_url = args.login_url
            if args.timeout:
                profile.session_config.timeout_hours = args.timeout
            
            # Add the profile
            success = self.website_manager.add_profile(profile, overwrite=args.overwrite)
            
            if success:
                print(f"✅ Successfully created website profile from template")
                print(f"   Template: {args.template}")
                print(f"   ID: {args.id}")
                print(f"   Name: {args.name}")
                print(f"   URL: {args.url}")
                return True
            else:
                print(f"❌ Failed to save website profile: {args.id}")
                return False
                
        except Exception as e:
            print(f"❌ Error creating from template: {e}")
            return False
    
    def search_websites(self, args) -> bool:
        """Search website profiles."""
        try:
            profiles = self.website_manager.search_profiles(args.query)
            
            if not profiles:
                print(f"🔍 No profiles found matching: {args.query}")
                return True
            
            print(f"🔍 Found {len(profiles)} profile(s) matching '{args.query}':")
            print()
            
            for i, profile in enumerate(profiles, 1):
                print(f"{i}. {profile.display_name}")
                print(f"   ID: {profile.website_id}")
                print(f"   URL: {profile.target_url}")
                print()
            
            return True
            
        except Exception as e:
            print(f"❌ Error searching websites: {e}")
            return False
    
    def export_websites(self, args) -> bool:
        """Export website profiles to JSON file."""
        try:
            profile_ids = args.ids if args.ids else None
            success = self.website_manager.export_profiles(args.output, profile_ids)
            
            if success:
                print(f"✅ Successfully exported profiles to: {args.output}")
                return True
            else:
                print(f"❌ Failed to export profiles")
                return False
                
        except Exception as e:
            print(f"❌ Error exporting websites: {e}")
            return False
    
    def import_websites(self, args) -> bool:
        """Import website profiles from JSON file."""
        try:
            if not Path(args.input).exists():
                print(f"❌ Input file not found: {args.input}")
                return False
            
            results = self.website_manager.import_profiles(args.input, overwrite=args.overwrite)
            
            successful = sum(1 for success in results.values() if success)
            total = len(results)
            
            print(f"📥 Import completed: {successful}/{total} profiles imported")
            
            # Show details
            for profile_id, success in results.items():
                status = "✅" if success else "❌"
                print(f"   {status} {profile_id}")
            
            return successful > 0
            
        except Exception as e:
            print(f"❌ Error importing websites: {e}")
            return False
    
    def list_templates(self, args) -> bool:
        """List available built-in templates."""
        try:
            templates = self.website_manager.list_templates()
            
            if not templates:
                print("📝 No built-in templates available")
                return True
            
            print(f"📋 Available Templates ({len(templates)}):")
            print()
            
            for template_id in templates:
                template = self.website_manager.get_template(template_id)
                if template:
                    print(f"• {template_id}")
                    print(f"  Name: {template.display_name}")
                    print(f"  URL: {template.target_url}")
                    print(f"  Auth: {template.auth_method.value}")
                    print()
            
            return True
            
        except Exception as e:
            print(f"❌ Error listing templates: {e}")
            return False
    
    def statistics(self, args) -> bool:
        """Show website profile statistics."""
        try:
            stats = self.website_manager.get_profile_statistics()
            
            print("📊 Website Profile Statistics")
            print("="*40)
            print(f"Total Profiles: {stats['total_profiles']}")
            print()
            
            if stats['auth_methods']:
                print("🔐 Authentication Methods:")
                for method, count in stats['auth_methods'].items():
                    print(f"   {method}: {count}")
                print()
            
            if stats['domains']:
                print("🌐 Top Domains:")
                sorted_domains = sorted(stats['domains'].items(), key=lambda x: x[1], reverse=True)
                for domain, count in sorted_domains[:10]:
                    print(f"   {domain}: {count}")
                print()
            
            if stats['available_templates']:
                print(f"📋 Available Templates: {len(stats['available_templates'])}")
                print(f"   {', '.join(stats['available_templates'])}")
            
            return True
            
        except Exception as e:
            print(f"❌ Error getting statistics: {e}")
            return False
    
    # Session Management Commands
    
    def list_sessions(self, args) -> bool:
        """List user sessions."""
        try:
            if args.username and args.website:
                # Get specific session
                session = self.session_manager.get_session(args.username, args.website)
                if session:
                    sessions = [session]
                else:
                    sessions = []
            elif args.username:
                # Get all sessions for user
                sessions = self.session_manager.get_user_sessions(args.username)
            elif args.website:
                # Get all sessions for website
                sessions = self.session_manager.get_website_sessions(args.website)
            else:
                # Get all active sessions
                sessions = list(self.session_manager._active_sessions.values())
            
            if not sessions:
                print("📝 No sessions found.")
                return True
            
            if args.format == "json":
                # JSON output
                sessions_data = [session.to_dict() for session in sessions]
                print(json.dumps(sessions_data, indent=2, ensure_ascii=False))
            else:
                # Table output
                print(f"📋 Found {len(sessions)} session(s):")
                print()
                
                for i, session in enumerate(sessions, 1):
                    status_icon = "✅" if session.is_valid() else "❌"
                    print(f"{i}. {status_icon} {session.username} @ {session.website_id}")
                    print(f"   Session ID: {session.session_id}")
                    print(f"   Status: {session.status.value}")
                    print(f"   Created: {session.created_at.strftime('%Y-%m-%d %H:%M:%S') if session.created_at else 'Unknown'}")
                    
                    if session.expires_at:
                        print(f"   Expires: {session.expires_at.strftime('%Y-%m-%d %H:%M:%S')}")
                        if session.is_expired():
                            print(f"   ⚠️  EXPIRED")
                    
                    cookies_count = len(session.auth_state.get('cookies', []))
                    print(f"   Cookies: {cookies_count}")
                    print()
            
            return True
            
        except Exception as e:
            print(f"❌ Error listing sessions: {e}")
            return False
    
    def delete_session(self, args) -> bool:
        """Delete a user session."""
        try:
            # Check if session exists
            session = self.session_manager.get_session(args.username, args.website)
            if not session:
                print(f"❌ Session not found: {args.username} @ {args.website}")
                return False
            
            # Confirm deletion unless forced
            if not args.force:
                print(f"⚠️  This will delete the session:")
                print(f"   User: {session.username}")
                print(f"   Website: {session.website_id}")
                print(f"   Session ID: {session.session_id}")
                
                confirm = input("\nAre you sure? (y/N): ").strip().lower()
                if confirm not in ['y', 'yes']:
                    print("🚫 Operation cancelled")
                    return False
            
            # Delete the session
            success = self.session_manager.delete_session(args.username, args.website)
            
            if success:
                print(f"✅ Successfully deleted session: {args.username} @ {args.website}")
                return True
            else:
                print(f"❌ Failed to delete session: {args.username} @ {args.website}")
                return False
                
        except Exception as e:
            print(f"❌ Error deleting session: {e}")
            return False
    
    def sync_sessions(self, args) -> bool:
        """Synchronize sessions with cloud storage."""
        try:
            print("☁️  Session synchronization functionality will be implemented")
            print("💡 Current sessions are automatically synced to cloud storage during login")
            
            # Show current session summary
            summary = self.session_manager.get_session_summary()
            print(f"\n📊 Current Session Summary:")
            print(f"   Total Sessions: {summary['total_sessions']}")
            print(f"   Active Users: {summary['active_users']}")
            print(f"   Websites: {summary['total_websites']}")
            
            return True
            
        except Exception as e:
            print(f"❌ Error syncing sessions: {e}")
            return False
    
    def clean_expired(self, args) -> bool:
        """Clean up expired sessions."""
        try:
            # Get validation report first
            validation = self.session_manager.validate_sessions()
            expired_count = len(validation['expired'])
            invalid_count = len(validation['invalid'])
            
            if expired_count == 0 and invalid_count == 0:
                print("✅ No expired or invalid sessions found")
                return True
            
            print(f"🔍 Found {expired_count} expired and {invalid_count} invalid sessions")
            
            if args.dry_run:
                print("\n🔍 Dry run - would clean up:")
                for session_key in validation['expired']:
                    print(f"   📅 Expired: {session_key}")
                for session_key in validation['invalid']:
                    print(f"   ❌ Invalid: {session_key}")
                return True
            
            # Clean up expired sessions
            cleaned_count = self.session_manager.clean_expired_sessions()
            
            print(f"✅ Cleaned up {cleaned_count} expired sessions")
            return True
            
        except Exception as e:
            print(f"❌ Error cleaning sessions: {e}")
            return False
    
    def session_statistics(self, args) -> bool:
        """Show session statistics."""
        try:
            summary = self.session_manager.get_session_summary()
            validation = self.session_manager.validate_sessions()
            
            print("📊 Session Statistics")
            print("="*40)
            print(f"Total Sessions: {summary['total_sessions']}")
            print(f"Active Users: {summary['active_users']}")
            print(f"Managed Websites: {summary['total_websites']}")
            print()
            
            print("📋 Session Status:")
            print(f"   Valid: {len(validation['valid'])}")
            print(f"   Expired: {len(validation['expired'])}")
            print(f"   Invalid: {len(validation['invalid'])}")
            print()
            
            if summary['sessions_by_website']:
                print("🌐 Sessions by Website:")
                for website, count in summary['sessions_by_website'].items():
                    print(f"   {website}: {count}")
                print()
            
            if summary['sessions_by_user']:
                print("👤 Sessions by User:")
                for user, count in summary['sessions_by_user'].items():
                    print(f"   {user}: {count}")
            
            return True
            
        except Exception as e:
            print(f"❌ Error getting session statistics: {e}")
            return False


def create_website_parser() -> argparse.ArgumentParser:
    """Create the website management argument parser."""
    parser = argparse.ArgumentParser(
        description='Multi-Website Login Management - Website Profile Manager',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
Examples:
  # Add a new website profile
  python manage.py add-website --id mysite --name "My Website" --url https://example.com
  
  # List all profiles
  python manage.py list-websites
  
  # Show detailed information
  python manage.py show-website --id mysite
  
  # Update a profile
  python manage.py update-website --id mysite --timeout 48
  
  # Remove a profile
  python manage.py remove-website --id mysite
  
  # Create from template
  python manage.py create-template --template geekbi --id mygeekbi --name "My GeekBI" --url https://my.geekbi.com
  
  # Search profiles
  python manage.py search-websites --query "geek"
        '''
    )
    
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Add website command
    add_parser = subparsers.add_parser('add-website', help='Add a new website profile')
    add_parser.add_argument('--id', required=True, help='Website identifier')
    add_parser.add_argument('--name', required=True, help='Display name')
    add_parser.add_argument('--url', required=True, help='Target URL')
    add_parser.add_argument('--login-url', help='Login page URL')
    add_parser.add_argument('--auth-method', choices=['manual', 'form', 'oauth', 'custom'], 
                           default='manual', help='Authentication method')
    add_parser.add_argument('--username-selector', help='CSS selector for username field')
    add_parser.add_argument('--password-selector', help='CSS selector for password field')
    add_parser.add_argument('--submit-selector', help='CSS selector for submit button')
    add_parser.add_argument('--viewport', help='Browser viewport (e.g., 1920x1080)')
    add_parser.add_argument('--timeout', type=int, help='Session timeout in hours')
    add_parser.add_argument('--overwrite', action='store_true', help='Overwrite existing profile')
    
    # List websites command
    list_parser = subparsers.add_parser('list-websites', help='List website profiles')
    list_parser.add_argument('--format', choices=['table', 'json'], default='table', help='Output format')
    list_parser.add_argument('--include-templates', action='store_true', help='Include built-in templates')
    
    # Show website command
    show_parser = subparsers.add_parser('show-website', help='Show website profile details')
    show_parser.add_argument('--id', required=True, help='Website identifier')
    
    # Update website command
    update_parser = subparsers.add_parser('update-website', help='Update website profile')
    update_parser.add_argument('--id', required=True, help='Website identifier')
    update_parser.add_argument('--name', help='Display name')
    update_parser.add_argument('--url', help='Target URL')
    update_parser.add_argument('--login-url', help='Login page URL')
    update_parser.add_argument('--auth-method', choices=['manual', 'form', 'oauth', 'custom'], 
                              help='Authentication method')
    update_parser.add_argument('--username-selector', help='CSS selector for username field')
    update_parser.add_argument('--password-selector', help='CSS selector for password field')
    update_parser.add_argument('--submit-selector', help='CSS selector for submit button')
    update_parser.add_argument('--viewport', help='Browser viewport (e.g., 1920x1080)')
    update_parser.add_argument('--timeout', type=int, help='Session timeout in hours')
    
    # Remove website command
    remove_parser = subparsers.add_parser('remove-website', help='Remove website profile')
    remove_parser.add_argument('--id', required=True, help='Website identifier')
    remove_parser.add_argument('--force', action='store_true', help='Skip confirmation')
    
    # Create from template command
    template_parser = subparsers.add_parser('create-template', help='Create profile from template')
    template_parser.add_argument('--template', required=True, help='Template identifier')
    template_parser.add_argument('--id', required=True, help='New website identifier')
    template_parser.add_argument('--name', required=True, help='Display name')
    template_parser.add_argument('--url', required=True, help='Target URL')
    template_parser.add_argument('--login-url', help='Login page URL')
    template_parser.add_argument('--timeout', type=int, help='Session timeout in hours')
    template_parser.add_argument('--overwrite', action='store_true', help='Overwrite existing profile')
    
    # Search websites command
    search_parser = subparsers.add_parser('search-websites', help='Search website profiles')
    search_parser.add_argument('--query', required=True, help='Search query')
    
    # Export websites command
    export_parser = subparsers.add_parser('export-websites', help='Export website profiles')
    export_parser.add_argument('--output', required=True, help='Output JSON file')
    export_parser.add_argument('--ids', nargs='+', help='Specific profile IDs to export')
    
    # Import websites command
    import_parser = subparsers.add_parser('import-websites', help='Import website profiles')
    import_parser.add_argument('--input', required=True, help='Input JSON file')
    import_parser.add_argument('--overwrite', action='store_true', help='Overwrite existing profiles')
    
    # List templates command
    templates_parser = subparsers.add_parser('list-templates', help='List built-in templates')
    
    # Statistics command
    stats_parser = subparsers.add_parser('statistics', help='Show profile statistics')
    
    # Session Management Commands
    
    # List sessions command
    list_sessions_parser = subparsers.add_parser('list-sessions', help='List user sessions')
    list_sessions_parser.add_argument('--username', help='Filter by username')
    list_sessions_parser.add_argument('--website', help='Filter by website ID')
    list_sessions_parser.add_argument('--format', choices=['table', 'json'], default='table', help='Output format')
    
    # Delete session command
    delete_session_parser = subparsers.add_parser('delete-session', help='Delete a user session')
    delete_session_parser.add_argument('--username', required=True, help='Username')
    delete_session_parser.add_argument('--website', required=True, help='Website ID')
    delete_session_parser.add_argument('--force', action='store_true', help='Skip confirmation')
    
    # Sync sessions command
    sync_sessions_parser = subparsers.add_parser('sync-sessions', help='Synchronize sessions with cloud')
    sync_sessions_parser.add_argument('--force', action='store_true', help='Force synchronization')
    sync_sessions_parser.add_argument('--direction', choices=['up', 'down', 'both'], default='both', help='Sync direction')
    
    # Clean expired command
    clean_expired_parser = subparsers.add_parser('clean-expired', help='Clean up expired sessions')
    clean_expired_parser.add_argument('--dry-run', action='store_true', help='Show what would be cleaned without doing it')
    
    # Session statistics command
    session_stats_parser = subparsers.add_parser('session-statistics', help='Show session statistics')
    
    return parser


def main():
    """Main entry point for website management CLI."""
    parser = create_website_parser()
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return False
    
    cli = WebsiteCLI()
    
    # Command dispatch
    command_handlers = {
        'add-website': cli.add_website,
        'list-websites': cli.list_websites,
        'show-website': cli.show_website,
        'update-website': cli.update_website,
        'remove-website': cli.remove_website,
        'create-template': cli.create_from_template,
        'search-websites': cli.search_websites,
        'export-websites': cli.export_websites,
        'import-websites': cli.import_websites,
        'list-templates': cli.list_templates,
        'statistics': cli.statistics,
        'list-sessions': cli.list_sessions,
        'delete-session': cli.delete_session,
        'sync-sessions': cli.sync_sessions,
        'clean-expired': cli.clean_expired,
        'session-statistics': cli.session_statistics
    }
    
    handler = command_handlers.get(args.command)
    if handler:
        try:
            success = handler(args)
            sys.exit(0 if success else 1)
        except KeyboardInterrupt:
            print("\n🚫 Operation cancelled by user")
            sys.exit(1)
        except Exception as e:
            print(f"💥 Unexpected error: {e}")
            sys.exit(1)
    else:
        print(f"❌ Unknown command: {args.command}")
        sys.exit(1)


if __name__ == "__main__":
    main()